package com.cupk.controllers;

import com.cupk.dtos.CreatePublicationRequest;
import com.cupk.dtos.MessageResponse;
import com.cupk.dtos.PublicationDto;
import com.cupk.dtos.PublicationStatsDto;
import com.cupk.dtos.UpdatePublicationRequest;
import com.cupk.services.PublicationService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;

import jakarta.validation.Valid;
import java.util.List;

/**
 * 成果发表管理控制器
 */
@Slf4j
@RestController
@RequestMapping("/publications")
@RequiredArgsConstructor
public class PublicationController {

    private final PublicationService publicationService;

    /**
     * 获取所有成果列表
     */
    @GetMapping
    @PreAuthorize("hasRole('ADMIN') or hasRole('RESEARCHER')")
    public ResponseEntity<List<PublicationDto>> getAllPublications() {
        log.info("获取所有成果列表请求");
        List<PublicationDto> publications = publicationService.getAllPublications();
        return ResponseEntity.ok(publications);
    }

    /**
     * 获取单个成果详情
     */
    @GetMapping("/{id}")
    @PreAuthorize("hasRole('ADMIN') or @publicationService.isPublicationAccessible(#id, authentication.name)")
    public ResponseEntity<PublicationDto> getPublicationById(@PathVariable Long id) {
        log.info("获取成果详情请求，ID: {}", id);
        PublicationDto publication = publicationService.getPublicationById(id);
        return ResponseEntity.ok(publication);
    }

    /**
     * 获取当前用户的成果列表
     */
    @GetMapping("/user")
    @PreAuthorize("isAuthenticated()")
    public ResponseEntity<List<PublicationDto>> getUserPublications(Authentication authentication) {
        String username = authentication.getName();
        log.info("获取用户成果列表请求，用户: {}", username);
        List<PublicationDto> publications = publicationService.getUserPublications(username);
        return ResponseEntity.ok(publications);
    }

    /**
     * 根据项目ID获取成果列表
     */
    @GetMapping("/project/{projectId}")
    @PreAuthorize("hasRole('ADMIN') or hasRole('RESEARCHER')")
    public ResponseEntity<List<PublicationDto>> getPublicationsByProject(@PathVariable Long projectId) {
        log.info("获取项目成果列表请求，项目ID: {}", projectId);
        List<PublicationDto> publications = publicationService.getPublicationsByProject(projectId);
        return ResponseEntity.ok(publications);
    }

    /**
     * 创建新成果
     */
    @PostMapping
    @PreAuthorize("hasRole('ADMIN') or hasRole('RESEARCHER')")
    public ResponseEntity<PublicationDto> createPublication(
            @Valid @RequestBody CreatePublicationRequest request,
            Authentication authentication) {
        String username = authentication.getName();
        log.info("创建成果请求，用户: {}, 成果: {}", username, request.getTitle());
        PublicationDto createdPublication = publicationService.createPublication(request, username);
        return ResponseEntity.status(HttpStatus.CREATED).body(createdPublication);
    }

    /**
     * 更新成果信息
     */
    @PutMapping("/{id}")
    @PreAuthorize("hasRole('ADMIN') or @publicationService.isPublicationAuthor(#id, authentication.name)")
    public ResponseEntity<PublicationDto> updatePublication(
            @PathVariable Long id,
            @Valid @RequestBody UpdatePublicationRequest request,
            Authentication authentication) {
        String username = authentication.getName();
        log.info("更新成果请求，用户: {}, 成果ID: {}", username, id);
        PublicationDto updatedPublication = publicationService.updatePublication(id, request);
        return ResponseEntity.ok(updatedPublication);
    }

    /**
     * 删除成果
     */
    @DeleteMapping("/{id}")
    @PreAuthorize("hasRole('ADMIN') or @publicationService.isPublicationAuthor(#id, authentication.name)")
    public ResponseEntity<MessageResponse> deletePublication(
            @PathVariable Long id,
            Authentication authentication) {
        String username = authentication.getName();
        log.info("删除成果请求，用户: {}, 成果ID: {}", username, id);
        publicationService.deletePublication(id);
        return ResponseEntity.ok(new MessageResponse("成果删除成功"));
    }

    /**
     * 搜索成果
     */
    @GetMapping("/search")
    @PreAuthorize("hasRole('ADMIN') or hasRole('RESEARCHER')")
    public ResponseEntity<List<PublicationDto>> searchPublications(@RequestParam String keyword) {
        log.info("搜索成果请求，关键词: {}", keyword);
        List<PublicationDto> publications = publicationService.searchPublications(keyword);
        return ResponseEntity.ok(publications);
    }

    /**
     * 获取成果统计信息
     */
    @GetMapping("/stats")
    @PreAuthorize("isAuthenticated()")
    public ResponseEntity<PublicationStatsDto> getPublicationStats(Authentication authentication) {
        String username = authentication.getName();
        log.info("获取成果统计信息请求，用户: {}", username);
        PublicationStatsDto stats = publicationService.getPublicationStats(username);
        return ResponseEntity.ok(stats);
    }
}
